#!/bin/bash

# 阿里云服务器环境配置脚本
# 用于配置文件上传服务所需的服务器环境

set -e

echo "=========================================="
echo "阿里云服务器文件上传服务环境配置"
echo "=========================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 配置变量
UPLOAD_DIR="/var/www/uploads"
WEB_USER="www-data"
SSH_USER="root"

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}错误: 请使用root用户运行此脚本${NC}"
    exit 1
fi

echo -e "${YELLOW}开始配置服务器环境...${NC}"

# 1. 更新系统包
echo "1. 更新系统包..."
apt update && apt upgrade -y

# 2. 安装必要的软件包
echo "2. 安装必要的软件包..."
apt install -y nginx openssh-server curl wget unzip

# 3. 创建上传目录
echo "3. 创建上传目录..."
mkdir -p $UPLOAD_DIR
chown -R $WEB_USER:$WEB_USER $UPLOAD_DIR
chmod -R 755 $UPLOAD_DIR

# 4. 配置Nginx
echo "4. 配置Nginx..."
cat > /etc/nginx/sites-available/uploads << EOF
server {
    listen 80;
    server_name _;
    
    # 文件上传目录
    location /uploads/ {
        alias $UPLOAD_DIR/;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
        
        # 允许跨域访问
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
        add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range";
        
        # 文件类型支持
        location ~* \.(jpg|jpeg|png|gif|bmp|webp)$ {
            expires 30d;
            add_header Cache-Control "public, immutable";
        }
        
        location ~* \.(mp3|wav|ogg|aac)$ {
            expires 7d;
            add_header Cache-Control "public";
        }
        
        # 大文件支持
        client_max_body_size 50M;
    }
    
    # 健康检查
    location /health {
        access_log off;
        return 200 "OK\n";
        add_header Content-Type text/plain;
    }
}
EOF

# 启用站点
ln -sf /etc/nginx/sites-available/uploads /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# 测试Nginx配置
nginx -t

# 重启Nginx
systemctl restart nginx
systemctl enable nginx

# 5. 配置SSH
echo "5. 配置SSH..."
# 备份SSH配置
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup

# 配置SSH
cat >> /etc/ssh/sshd_config << EOF

# 文件上传服务配置
# 允许密码认证
PasswordAuthentication yes
# 允许公钥认证
PubkeyAuthentication yes
# 允许SFTP
Subsystem sftp /usr/lib/openssh/sftp-server
# 连接超时
ClientAliveInterval 60
ClientAliveCountMax 3
EOF

# 重启SSH服务
systemctl restart ssh
systemctl enable ssh

# 6. 创建专用用户（可选）
echo "6. 创建专用用户..."
read -p "是否创建专用的文件上传用户？(y/n): " create_user

if [ "$create_user" = "y" ] || [ "$create_user" = "Y" ]; then
    read -p "请输入用户名: " upload_user
    read -s -p "请输入密码: " upload_pass
    echo
    
    # 创建用户
    useradd -m -s /bin/bash $upload_user
    echo "$upload_user:$upload_pass" | chpasswd
    
    # 添加到www-data组
    usermod -a -G www-data $upload_user
    
    # 设置目录权限
    chown -R $upload_user:www-data $UPLOAD_DIR
    chmod -R 775 $UPLOAD_DIR
    
    echo -e "${GREEN}用户 $upload_user 创建成功${NC}"
fi

# 7. 配置防火墙
echo "7. 配置防火墙..."
# 安装ufw（如果未安装）
if ! command -v ufw &> /dev/null; then
    apt install -y ufw
fi

# 配置防火墙规则
ufw allow ssh
ufw allow 'Nginx Full'
ufw --force enable

# 8. 创建监控脚本
echo "8. 创建监控脚本..."
cat > /usr/local/bin/check-uploads.sh << 'EOF'
#!/bin/bash

UPLOAD_DIR="/var/www/uploads"
LOG_FILE="/var/log/uploads-monitor.log"

# 检查目录是否存在
if [ ! -d "$UPLOAD_DIR" ]; then
    echo "$(date): 错误 - 上传目录不存在: $UPLOAD_DIR" >> $LOG_FILE
    exit 1
fi

# 检查目录权限
if [ ! -r "$UPLOAD_DIR" ] || [ ! -w "$UPLOAD_DIR" ]; then
    echo "$(date): 错误 - 上传目录权限不正确: $UPLOAD_DIR" >> $LOG_FILE
    exit 1
fi

# 检查磁盘空间
DISK_USAGE=$(df "$UPLOAD_DIR" | tail -1 | awk '{print $5}' | sed 's/%//')
if [ "$DISK_USAGE" -gt 90 ]; then
    echo "$(date): 警告 - 磁盘使用率过高: ${DISK_USAGE}%" >> $LOG_FILE
fi

# 检查Nginx状态
if ! systemctl is-active --quiet nginx; then
    echo "$(date): 错误 - Nginx服务未运行" >> $LOG_FILE
    systemctl restart nginx
fi

echo "$(date): 检查完成 - 磁盘使用率: ${DISK_USAGE}%" >> $LOG_FILE
EOF

chmod +x /usr/local/bin/check-uploads.sh

# 添加到crontab
(crontab -l 2>/dev/null; echo "*/5 * * * * /usr/local/bin/check-uploads.sh") | crontab -

# 9. 创建清理脚本
echo "9. 创建清理脚本..."
cat > /usr/local/bin/cleanup-uploads.sh << 'EOF'
#!/bin/bash

UPLOAD_DIR="/var/www/uploads"
DAYS_TO_KEEP=30

echo "开始清理 $DAYS_TO_KEEP 天前的文件..."

# 查找并删除旧文件
find "$UPLOAD_DIR" -type f -mtime +$DAYS_TO_KEEP -delete

# 删除空目录
find "$UPLOAD_DIR" -type d -empty -delete

echo "清理完成: $(date)"
EOF

chmod +x /usr/local/bin/cleanup-uploads.sh

# 添加到crontab（每天凌晨2点执行）
(crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/cleanup-uploads.sh") | crontab -

# 10. 显示配置信息
echo -e "${GREEN}==========================================${NC}"
echo -e "${GREEN}服务器环境配置完成！${NC}"
echo -e "${GREEN}==========================================${NC}"
echo ""
echo "配置信息："
echo "- 上传目录: $UPLOAD_DIR"
echo "- Nginx配置: /etc/nginx/sites-available/uploads"
echo "- SSH端口: 22"
echo "- 防火墙: 已启用"
echo ""
echo "服务状态："
systemctl status nginx --no-pager -l
echo ""
systemctl status ssh --no-pager -l
echo ""
echo "目录权限："
ls -la $UPLOAD_DIR
echo ""
echo "测试命令："
echo "- 测试Nginx: curl http://localhost/health"
echo "- 测试目录: curl http://localhost/uploads/"
echo "- 检查磁盘: df -h $UPLOAD_DIR"
echo ""
echo -e "${YELLOW}请确保在应用配置中设置正确的服务器信息：${NC}"
echo "- 服务器IP: $(curl -s ifconfig.me)"
echo "- SSH端口: 22"
echo "- 上传目录: $UPLOAD_DIR"
echo "- 访问URL: http://$(curl -s ifconfig.me)/uploads/"
echo ""
echo -e "${GREEN}配置完成！${NC}" 